#include "mainwindow.h"
#include <QPainter>
#include <QFont>
#include <QDebug>
#include <QRandomGenerator>
#include <QPixmap>
#include <QVBoxLayout>
#include <QHBoxLayout>

// 构造函数
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    // 加载图片资源
    playerIdlePixmap.load(":/player_idle.png");
    playerSwingPixmap.load(":/player_swing.png");
    baseballPixmap.load(":/baseball.png");
    backgroundPixmap.load(":/background.png");
    startMenuBackground.load(":/start_menu_bg.png");

    // 检查图片是否加载成功
    if(playerIdlePixmap.isNull()) qDebug() << "Failed to load player_idle.png";
    if(playerSwingPixmap.isNull()) qDebug() << "Failed to load player_swing.png";
    if(baseballPixmap.isNull()) qDebug() << "Failed to load baseball.png";
    if(backgroundPixmap.isNull()) qDebug() << "Failed to load background.png";
    if(startMenuBackground.isNull()) qDebug() << "Failed to load start_menu_bg.png";

    // 初始化菜单
    initMenu();

    // 初始化游戏
    initGame();

    // 设置窗口背景色
    setStyleSheet("background-color: #0a0a2a;");

    qDebug() << "MainWindow initialized successfully";
}

// 析构函数
MainWindow::~MainWindow()
{
    qDebug() << "MainWindow destructor called";

    // 安全地停止和删除计时器
    if(gameTimer) {
        if(gameTimer->isActive()) {
            gameTimer->stop();
        }
        delete gameTimer;
        gameTimer = nullptr;
    }
}

// 初始化菜单
void MainWindow::initMenu()
{
    qDebug() << "Initializing menu";

    // 创建按钮
    startButton = new QPushButton("开始游戏", this);
    leaderboardButton = new QPushButton("排行榜", this);
    settingsButton = new QPushButton("游戏设置", this);
    exitButton = new QPushButton("退出游戏", this);

    // 设置按钮样式
    QString buttonStyle =
        "QPushButton {"
        "    background-color: #FF6B35;"
        "    color: white;"
        "    border: 2px solid #FF8C42;"
        "    border-radius: 15px;"
        "    font-size: 18px;"
        "    font-weight: bold;"
        "    padding: 12px 24px;"
        "    min-width: 150px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #FF8C42;"
        "    border: 2px solid #FFA95C;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #E55A2B;"
        "}";

    startButton->setStyleSheet(buttonStyle);
    leaderboardButton->setStyleSheet(buttonStyle);
    settingsButton->setStyleSheet(buttonStyle);
    exitButton->setStyleSheet(buttonStyle);

    // 连接按钮信号
    connect(startButton, &QPushButton::clicked, this, &MainWindow::startGame);
    connect(leaderboardButton, &QPushButton::clicked, this, &MainWindow::showLeaderboard);
    connect(settingsButton, &QPushButton::clicked, this, &MainWindow::showSettings);
    connect(exitButton, &QPushButton::clicked, this, &MainWindow::exitGame);

    // 设置按钮初始可见性
    startButton->setVisible(true);
    leaderboardButton->setVisible(true);
    settingsButton->setVisible(true);
    exitButton->setVisible(true);
}

// 初始化游戏
void MainWindow::initGame()
{
    qDebug() << "Initializing game";

    // 重置游戏状态
    score = 0;
    combo = 0;
    maxCombo = 0;
    totalNotes = 0;
    hitNotes = 0;
    life = 10;
    maxLife = 10;

    // 重置游戏难度
    baseSpeed = 5.0;
    speedMultiplier = 1.0;
    minSpawnInterval = 45;
    maxSpawnInterval = 75;
    nextSpawnThreshold = QRandomGenerator::global()->bounded(minSpawnInterval, maxSpawnInterval + 1);

    // 玩家初始位置和状态
    playerX = 100;
    playerY = 450;
    isSwinging = false;
    swingTimer = 0;
    currentLane = 1;

    targetLane = 1;
    moveSpeed = 8;
    isMoving = false;

    // 清空音符和判定显示
    notes.clear();
    judgementDisplays.clear();
    spawnCounter = 0;

    // 创建游戏计时器（如果不存在）
    if(!gameTimer) {
        gameTimer = new QTimer(this);
        connect(gameTimer, &QTimer::timeout, this, &MainWindow::updateGame);
    }

    // 注意：这里不启动计时器，等开始游戏后再启动
}
// 初始化结算界面
void MainWindow::initGameOver()
{
    qDebug() << "Initializing game over screen";

    // 创建结算界面按钮
    restartButton = new QPushButton("再来一局", this);
    quitButton = new QPushButton("不玩了", this);

    // 设置按钮样式
    QString buttonStyle =
        "QPushButton {"
        "    background-color: #FF6B35;"
        "    color: white;"
        "    border: 2px solid #FF8C42;"
        "    border-radius: 15px;"
        "    font-size: 18px;"
        "    font-weight: bold;"
        "    padding: 12px 24px;"
        "    min-width: 150px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #FF8C42;"
        "    border: 2px solid #FFA95C;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #E55A2B;"
        "}";

    restartButton->setStyleSheet(buttonStyle);
    quitButton->setStyleSheet(buttonStyle);

    // 连接按钮信号
    connect(restartButton, &QPushButton::clicked, this, &MainWindow::restartGame);
    connect(quitButton, &QPushButton::clicked, this, &MainWindow::exitGame);

    restartButton->setVisible(false);
    quitButton->setVisible(false);
}

// 绘图事件
void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    switch(gameState) {
    case START_MENU:
        drawStartMenu(painter);
        break;
    case PLAYING:
        drawBackground(painter);
        drawNotes(painter);
        drawPlayer(painter);
        drawUI(painter);
        break;
    case GAME_OVER:
        drawGameOver(painter);
        break;
    }
}

// 绘制起始菜单
void MainWindow::drawStartMenu(QPainter &painter)
{
    // 绘制背景图
    if(!startMenuBackground.isNull()) {
        painter.drawPixmap(0, 0, width(), height(), startMenuBackground);
    } else {
        painter.fillRect(0, 0, width(), height(), QColor(10, 10, 42));
    }

    // 添加半透明遮罩让文字更清晰
    painter.setBrush(QColor(0, 0, 0, 150));
    painter.setPen(Qt::NoPen);
    painter.drawRect(0, 0, width(), height());

    // 设置按钮位置（居中）
    int centerX = width() / 2;
    int buttonY = height() / 2;
    int buttonWidth = 200;
    int buttonHeight = 50;
    int spacing = 20;

    if(startButton) startButton->setGeometry(centerX - buttonWidth/2, buttonY, buttonWidth, buttonHeight);
    if(leaderboardButton) leaderboardButton->setGeometry(centerX - buttonWidth/2, buttonY + buttonHeight + spacing, buttonWidth, buttonHeight);
    if(settingsButton) settingsButton->setGeometry(centerX - buttonWidth/2, buttonY + 2*(buttonHeight + spacing), buttonWidth, buttonHeight);
    if(exitButton) exitButton->setGeometry(centerX - buttonWidth/2, buttonY + 3*(buttonHeight + spacing), buttonWidth, buttonHeight);

    // 绘制游戏标题
    painter.setPen(QColor(255, 215, 0));
    painter.setFont(QFont("微软雅黑", 36, QFont::Bold));
    painter.drawText(centerX - 150, 150, "棒球节奏游戏");

    // 绘制副标题
    painter.setPen(QColor(200, 200, 200));
    painter.setFont(QFont("微软雅黑", 16));
    painter.drawText(centerX - 100, 200, "Baseball Rhythm Game");

    // 绘制操作提示
    painter.setPen(QColor(150, 150, 150));
    painter.setFont(QFont("Arial", 12));
    painter.drawText(centerX - 100, height() - 50, "使用 D F J K 键控制击球");
}

// 绘制结算界面
// 修改绘制结算界面函数
// 美化绘制结算界面函数
// 修改后的美化绘制结算界面函数
void MainWindow::drawGameOver(QPainter &painter)
{
    // 使用渐变背景 - 深蓝到黑色的渐变
    QLinearGradient gradient(0, 0, 0, height());
    gradient.setColorAt(0, QColor(15, 15, 45));
    gradient.setColorAt(1, QColor(5, 5, 20));
    painter.fillRect(0, 0, width(), height(), gradient);

    // 添加星空效果 - 随机小白点
    painter.setPen(Qt::white);
    for(int i = 0; i < 50; i++) {
        int x = QRandomGenerator::global()->bounded(width());
        int y = QRandomGenerator::global()->bounded(height());
        int size = QRandomGenerator::global()->bounded(1, 3);
        painter.drawEllipse(x, y, size, size);
    }

    // 添加顶部光晕效果
    QRadialGradient headerGradient(width()/2, -100, 600);
    headerGradient.setColorAt(0, QColor(255, 215, 0, 80));
    headerGradient.setColorAt(1, QColor(255, 215, 0, 0));
    painter.setBrush(headerGradient);
    painter.setPen(Qt::NoPen);
    painter.drawRect(0, 0, width(), 300);

    int centerX = width() / 2;
    int topY = height() / 6; // 从更上方开始

    // 安全地设置按钮位置（保持不变）
    if(restartButton && quitButton) {
        int buttonWidth = 220;
        int buttonHeight = 55;
        int spacing = 25;
        int buttonY = height() * 3 / 4;

        // 美化按钮样式
        QString buttonStyle =
            "QPushButton {"
            "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #6a11cb, stop:1 #2575fc);"
            "    color: white;"
            "    border: none;"
            "    border-radius: 12px;"
            "    font-size: 18px;"
            "    font-weight: bold;"
            "    padding: 12px 24px;"
            "    min-width: 150px;"
            "}"
            "QPushButton:hover {"
            "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #7e22cc, stop:1 #3b82f6);"
            "    border: 2px solid #ffffff;"
            "}"
            "QPushButton:pressed {"
            "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #581c87, stop:1 #1e40af);"
            "}";

        restartButton->setStyleSheet(buttonStyle);
        quitButton->setStyleSheet(buttonStyle);

        restartButton->setGeometry(centerX - buttonWidth/2, buttonY, buttonWidth, buttonHeight);
        quitButton->setGeometry(centerX - buttonWidth/2, buttonY + buttonHeight + spacing, buttonWidth, buttonHeight);
    }

    // 计算准确率
    int accuracy = totalNotes > 0 ? (hitNotes * 100) / totalNotes : 0;

    // 绘制评价卡片背景 - 放在最上方
    painter.setBrush(QColor(40, 40, 70, 220));
    painter.setPen(QPen(QColor(255, 215, 0), 2));
    painter.drawRoundedRect(centerX - 160, topY, 320, 80, 12, 12);

    // 绘制评价
    QString evaluation;
    QColor evalColor;

    if(accuracy >= 90) {
        evaluation = "🌟 全垒打大师！ 🌟";
        evalColor = QColor(255, 215, 0); // 金色
    } else if(accuracy >= 80) {
        evaluation = "⚡ 优秀击球手！ ⚡";
        evalColor = QColor(0, 255, 255); // 青色
    } else if(accuracy >= 70) {
        evaluation = "🔥 不错的发挥 🔥";
        evalColor = QColor(0, 255, 0);   // 绿色
    } else if(accuracy >= 60) {
        evaluation = "🎯 还需练习 🎯";
        evalColor = QColor(255, 165, 0); // 橙色
    } else {
        evaluation = "💪 继续加油 💪";
        evalColor = QColor(255, 100, 100); // 红色
    }

    painter.setPen(evalColor);
    painter.setFont(QFont("微软雅黑", 20, QFont::Bold));
    painter.drawText(centerX - 160, topY, 320, 80, Qt::AlignCenter, evaluation);

    // 绘制分数卡片背景 - 放在评价下方
    painter.setBrush(QColor(50, 50, 80, 200));
    painter.setPen(QPen(QColor(255, 105, 180), 2));
    painter.drawRoundedRect(centerX - 150, topY + 100, 300, 70, 10, 10);

    // 绘制分数信息
    painter.setPen(QColor(255, 255, 255));
    painter.setFont(QFont("微软雅黑", 16, QFont::Normal));
    painter.drawText(centerX - 150, topY + 100, 300, 30, Qt::AlignCenter, "最终得分");

    painter.setPen(QColor(255, 215, 0));
    painter.setFont(QFont("微软雅黑", 28, QFont::Bold));
    painter.drawText(centerX - 150, topY + 130, 300, 40, Qt::AlignCenter, QString::number(score));

    // 绘制详细统计卡片背景 - 放在分数下方
    painter.setBrush(QColor(40, 40, 70, 180));
    painter.setPen(QPen(QColor(100, 200, 255), 1));
    painter.drawRoundedRect(centerX - 200, topY + 190, 400, 160, 10, 10);

    // 绘制详细统计 - 使用表格形式
    int statStartY = topY + 210;
    int lineHeight = 35;

    // 表头
    painter.setPen(QColor(200, 200, 255));
    painter.setFont(QFont("微软雅黑", 14, QFont::Bold));
    painter.drawText(centerX - 200, statStartY - 25, 400, 25, Qt::AlignCenter, "游戏统计");

    // 绘制分隔线
    painter.setPen(QPen(QColor(100, 100, 150), 1));
    painter.drawLine(centerX - 180, statStartY - 5, centerX + 180, statStartY - 5);

    // 统计项目
    painter.setPen(QColor(200, 200, 200));
    painter.setFont(QFont("微软雅黑", 12));

    // 最大连击
    painter.drawText(centerX - 180, statStartY, 150, lineHeight, Qt::AlignLeft, "最大连击");
    painter.setPen(QColor(255, 215, 0));
    painter.drawText(centerX + 30, statStartY, 150, lineHeight, Qt::AlignRight, QString("%1").arg(maxCombo));

    // 击中率
    painter.setPen(QColor(200, 200, 200));
    painter.drawText(centerX - 180, statStartY + lineHeight, 150, lineHeight, Qt::AlignLeft, "击中率");
    // 根据击中率设置颜色
    QColor accuracyColor;
    if(accuracy >= 90) accuracyColor = QColor(0, 255, 0);
    else if(accuracy >= 70) accuracyColor = QColor(255, 215, 0);
    else accuracyColor = QColor(255, 100, 100);
    painter.setPen(accuracyColor);
    painter.drawText(centerX + 30, statStartY + lineHeight, 150, lineHeight, Qt::AlignRight, QString("%1%").arg(accuracy));

    // 击中数
    painter.setPen(QColor(200, 200, 200));
    painter.drawText(centerX - 180, statStartY + lineHeight * 2, 150, lineHeight, Qt::AlignLeft, "击中数");
    painter.setPen(QColor(135, 206, 250));
    painter.drawText(centerX + 30, statStartY + lineHeight * 2, 150, lineHeight, Qt::AlignRight, QString("%1/%2").arg(hitNotes).arg(totalNotes));

    // 剩余生命
    painter.setPen(QColor(200, 200, 200));
    painter.drawText(centerX - 180, statStartY + lineHeight * 3, 150, lineHeight, Qt::AlignLeft, "剩余生命");
    // 根据剩余生命设置颜色
    QColor lifeColor;
    if(life > 7) lifeColor = QColor(0, 255, 0);
    else if(life > 3) lifeColor = QColor(255, 215, 0);
    else lifeColor = QColor(255, 100, 100);
    painter.setPen(lifeColor);
    painter.drawText(centerX + 30, statStartY + lineHeight * 3, 150, lineHeight, Qt::AlignRight, QString("%1").arg(life));

    // 添加底部装饰性棒球图标
    if(!baseballPixmap.isNull()) {
        painter.setOpacity(0.1);
        int ballSize = 120;
        painter.drawPixmap(centerX - ballSize/2, height() - 100, ballSize, ballSize, baseballPixmap);
        painter.setOpacity(1.0);
    }

    // 添加版权信息
    //painter.setPen(QColor(100, 100, 150));
   // painter.setFont(QFont("Arial", 10));
   // painter.drawText(width() - 150, height() - 20, "Baseball Rhythm Game");
}
// 开始游戏
void MainWindow::startGame()
{
    qDebug() << "Starting game";

    gameState = PLAYING;

    // 隐藏菜单按钮
    if(startButton) startButton->setVisible(false);
    if(leaderboardButton) leaderboardButton->setVisible(false);
    if(settingsButton) settingsButton->setVisible(false);
    if(exitButton) exitButton->setVisible(false);

    // 启动游戏计时器
    if(gameTimer) {
        gameTimer->start(16);
    }

    update();
}

// 重新开始游戏
void MainWindow::restartGame()
{
    qDebug() << "Restarting game";

    // 隐藏结算界面按钮
    if(restartButton) restartButton->setVisible(false);
    if(quitButton) quitButton->setVisible(false);

    // 重置游戏状态
    gameState = PLAYING;

    // 重新初始化游戏
    initGame();

    // 启动游戏计时器
    if(gameTimer) {
        gameTimer->start(16);
    }

    update();
}

// 退出游戏
void MainWindow::exitGame()
{
    qDebug() << "Exiting game";
    QApplication::quit();
}

// 显示排行榜
void MainWindow::showLeaderboard()
{
    qDebug() << "Showing leaderboard";
}

// 显示设置
void MainWindow::showSettings()
{
    qDebug() << "Showing settings";
}

// 结束游戏
void MainWindow::endGame()
{
    qDebug() << "Ending game, life:" << life;

    // 先停止计时器
    if(gameTimer && gameTimer->isActive()) {
        gameTimer->stop();
    }

    // 改变游戏状态
    gameState = GAME_OVER;

    // 初始化结算界面（如果还没有初始化）
    if(!restartButton || !quitButton) {
        initGameOver();
    }

    // 显示结算界面按钮
    if(restartButton) restartButton->setVisible(true);
    if(quitButton) quitButton->setVisible(true);

    update();
}

// 新增更新游戏难度函数
void MainWindow::updateDifficulty()
{
    // 根据分数调整速度倍率
    // 每1000分增加0.1倍速度，最高不超过3倍
    speedMultiplier = 1.0 + (score / 1000.0) * 0.1;
    if(speedMultiplier > 3.0) {
        speedMultiplier = 3.0;
    }

    // 根据分数调整生成间隔
    // 每500分减少最小和最大生成间隔，最低不低于20和40
    int intervalReduction = score / 500;
    minSpawnInterval = qMax(20, 45 - intervalReduction);
    maxSpawnInterval = qMax(40, 75 - intervalReduction);

    // 每1000分在UI上显示难度提升提示
    static int lastDifficultyNotice = 0;
    if(score / 1000 > lastDifficultyNotice) {
        lastDifficultyNotice = score / 1000;
        if(lastDifficultyNotice > 0) {
            // 显示难度提升提示
            int centerX = width() / 2;
            int centerY = height() / 2;
            QString difficultyText = QString("难度提升! 速度 x%1").arg(QString::number(speedMultiplier, 'f', 1));
            judgementDisplays.append({HOMERUN, centerX, centerY, 90, difficultyText, QColor(255, 100, 255)});
        }
    }
}


// 游戏更新
void MainWindow::updateGame()
{
    // 检查游戏是否应该结束
    if(life <= 0 && gameState == PLAYING) {
        qDebug() << "Life reached 0, ending game";
        endGame();
        return;
    }

    // 确保只有在游戏进行中才更新
    if(gameState != PLAYING) {
        return;
    }

    // 根据分数调整游戏难度
    updateDifficulty();

    // 更新玩家轨道移动
    if(isMoving) {
        if(currentLane < targetLane) {
            currentLane++;
        } else if(currentLane > targetLane) {
            currentLane--;
        }

        if(currentLane == targetLane) {
            isMoving = false;
        }
    }

    // 更新挥棒状态
    if(isSwinging) {
        swingTimer--;
        if(swingTimer <= 0) {
            isSwinging = false;
        }
    }

    // 更新判定显示
    for(int i = judgementDisplays.size() - 1; i >= 0; i--) {
        judgementDisplays[i].timer--;
        judgementDisplays[i].y -= 1;

        if(judgementDisplays[i].timer <= 0) {
            judgementDisplays.remove(i);
        }
    }

    // 更新音符位置
    for(int i = notes.size() - 1; i >= 0; i--) {
        // 使用每个音符自己的速度（如果有）或基础速度
        double noteSpeed = baseSpeed * speedMultiplier;
        notes[i].x -= noteSpeed;

        // 检查是否错过击球
        if(notes[i].x < 70 && !notes[i].hit && !notes[i].missed) {
            notes[i].missed = true;
            combo = 0;

            // 错过音符扣减生命值
            life--;
            if(life < 0) life = 0;

            int noteY = 150 + notes[i].lane * 100 + 50;
            judgementDisplays.append({MISS, notes[i].x, noteY - 40, 45, "💥失误 -1生命", Qt::red});
        }

        // 移除超出屏幕的音符
        if(notes[i].x < -30 || notes[i].hit) {
            notes.remove(i);
        }
    }

    // 生成新音符 - 使用随机间隔
    spawnCounter++;
    if(spawnCounter >= nextSpawnThreshold) {
        spawnCounter = 0;
        spawnNote();
        // 设置下一次生成的时间间隔
        nextSpawnThreshold = QRandomGenerator::global()->bounded(minSpawnInterval, maxSpawnInterval + 1);
    }

    // 请求重绘
    update();
}

// 生成新音符
void MainWindow::spawnNote()
{
    int lane = QRandomGenerator::global()->bounded(4);
    // 确保音符从屏幕最右侧生成
    int startX = width() + 30; // 从屏幕右侧外30像素开始
    notes.append({lane, startX, false, false});
    totalNotes++;
}
// 键盘按下事件
void MainWindow::keyPressEvent(QKeyEvent *event)
{
    // 如果在结算界面，只处理特定按键
    if(gameState == GAME_OVER) {
        if(event->key() == Qt::Key_R) {
            restartGame();
        } else if(event->key() == Qt::Key_Escape) {
            exitGame();
        }
        return;
    }

    // 如果在开始菜单，不处理游戏按键
    if(gameState == START_MENU) {
        QMainWindow::keyPressEvent(event);
        return;
    }

    int lane = -1;

    // 检查按下的键
    switch(event->key()) {
    case Qt::Key_D:
        lane = 0;
        currentLane = 0;
        break;
    case Qt::Key_F:
        lane = 1;
        currentLane = 1;
        break;
    case Qt::Key_J:
        lane = 2;
        currentLane = 2;
        break;
    case Qt::Key_K:
        lane = 3;
        currentLane = 3;
        break;
    case Qt::Key_R:
        // R键重新开始游戏
        resetGame();
        return;
    default:
        QMainWindow::keyPressEvent(event);
        return;
    }

    // 触发挥棒动作
    isSwinging = true;
    swingTimer = 10;

    // 检查击球
    checkHit(lane);
}

// 检查击球
void MainWindow::checkHit(int lane)
{
    bool hitSuccess = false;

    for(Note &note : notes) {
        if(note.lane == currentLane && !note.hit && !note.missed) {
            // 扩大判定范围
            if(note.x >= 80 && note.x <= 220) {
                note.hit = true;
                hitSuccess = true;
                hitNotes++;

                // 更新最大连击数
                if(combo > maxCombo) {
                    maxCombo = combo;
                }

                // 计算距离判定线的距离
                int distance = abs(note.x - 150);
                Judgement judgement;
                int points = 0;
                QString text = "";
                QColor color = Qt::white;

                // 棒球主题分级判定
                if(distance <= 20) {
                    judgement = HOMERUN;
                    points = 300;
                    text = "全垒打!!!";
                    color = QColor(255, 215, 0);
                } else if(distance <= 50) {
                    judgement = GOODBALL;
                    points = 200;
                    text = "好球!!";
                    color = QColor(0, 255, 0);
                } else if(distance <= 80) {
                    judgement = SINGLEHIT;
                    points = 100;
                    text = "安打!";
                    color = QColor(135, 206, 250);
                } else {
                    judgement = FOUL;
                    points = 50;
                    text = "界外球";
                    color = QColor(255, 165, 0);
                }

                score += points + combo * 5;
                combo++;

                // 在对应轨道的击球位置显示判定词
                int noteY = 150 + note.lane * 100 + 50;
                judgementDisplays.append({judgement, note.x, noteY - 40, 45, text, color});

                break;
            }
        }
    }

    // 如果按下按键但没有击中任何音符，显示未击中
    if (!hitSuccess) {
        int displayY = 150 + lane * 100 + 50;

        // 未击中扣减生命值
        life--;
        if(life < 0) life = 0;

        // 在未击中时显示
        judgementDisplays.append({MISS, 150, displayY - 40, 45, "💥未击中 -1生命", Qt::red});

        // 空挥减少连击
        if (combo > 0) {
            combo--;
        }
    }
}

// 重置游戏
void MainWindow::resetGame()
{
    initGame();
    update();
}

// 绘制背景和轨道
void MainWindow::drawBackground(QPainter &painter)
{
    // 绘制背景图（拉伸填充整个窗口）
    if(!backgroundPixmap.isNull()) {
        painter.drawPixmap(0, 0, width(), height(), backgroundPixmap);
    } else {
        // 如果背景图加载失败，使用原来的颜色背景
        painter.fillRect(0, 0, width(), height(), QColor(10, 10, 42));
    }

    // 在背景上绘制半透明遮罩，让轨道更清晰
    painter.setBrush(QColor(0, 0, 0, 100));
    painter.setPen(Qt::NoPen);
    painter.drawRect(0, 0, width(), height());

    // 轨道设置
    const int LANE_COUNT = 4;
    const int LANE_WIDTH = 100;
    const int START_Y = 150;
    const int HIT_LINE_X = 150;

    // 绘制轨道水平线
    painter.setPen(QPen(Qt::white, 2));
    for(int i = 0; i <= LANE_COUNT; i++) {
        int y = START_Y + i * LANE_WIDTH;
        painter.drawLine(0, y, width(), y);
    }

    // 绘制击球区域红色竖线 - 覆盖所有轨道
    int topY = START_Y;
    int bottomY = START_Y + LANE_COUNT * LANE_WIDTH;  // 覆盖所有轨道
    painter.setPen(QPen(Qt::red, 4));
    painter.drawLine(HIT_LINE_X, topY, HIT_LINE_X, bottomY);

    // 绘制按键提示
    QStringList keys = {"D", "F", "J", "K"};
    painter.setFont(QFont("Arial", 16, QFont::Bold));
    painter.setPen(QPen(Qt::cyan));
    for(int i = 0; i < LANE_COUNT; i++) {
        int centerY = START_Y + i * LANE_WIDTH + LANE_WIDTH / 2;
        painter.drawText(50, centerY + 5, keys[i]);
    }
}

// 绘制玩家角色
void MainWindow::drawPlayer(QPainter &painter)
{
    // 根据当前轨道计算Y坐标
    int playerDrawY = 150 + currentLane * 100 + 10;

    // 根据状态选择图片
    QPixmap *currentPixmap;
    if(isSwinging && swingTimer > 5) {
        currentPixmap = &playerSwingPixmap;
    } else {
        currentPixmap = &playerIdlePixmap;
    }

    // 绘制玩家图片 - 使用 playerDrawY 而不是 playerY
    painter.drawPixmap(playerX, playerDrawY, 85, 100, *currentPixmap);
}

// 绘制音符
void MainWindow::drawNotes(QPainter &painter)
{
    for(const Note &note : notes) {
        // 计算音符在轨道上的y坐标
        int noteY = 150 + note.lane * 100 + 50;

        // 保存painter的原始状态
        painter.save();

        if(note.missed) {
            // 错过状态：添加红色遮罩
            painter.setOpacity(0.6); // 设置透明度
            QPixmap redBall = baseballPixmap;
            QPainter pixmapPainter(&redBall);
            pixmapPainter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
            pixmapPainter.fillRect(redBall.rect(), QColor(255, 0, 0, 150));
            painter.drawPixmap(note.x - 15, noteY - 15, 30, 30, redBall);
        } else if(note.hit) {
            // 击中状态：添加绿色遮罩
            painter.setOpacity(0.6);
            QPixmap greenBall = baseballPixmap;
            QPainter pixmapPainter(&greenBall);
            pixmapPainter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
            pixmapPainter.fillRect(greenBall.rect(), QColor(0, 255, 0, 150));
            painter.drawPixmap(note.x - 15, noteY - 15, 30, 30, greenBall);
        } else {
            // 正常状态：直接绘制棒球图片
            painter.setOpacity(1.0); // 完全不透明
            painter.drawPixmap(note.x - 15, noteY - 15, 30, 30, baseballPixmap);
        }

        // 恢复painter的原始状态
        painter.restore();
    }
}

// 绘制用户界面
void MainWindow::drawUI(QPainter &painter)
{
    // 设置字体
    QFont labelFont("Arial", 14, QFont::Bold);
    QFont valueFont("Arial", 24, QFont::Bold);

    // 分数显示 - 文字在上，数字在下
    painter.setFont(labelFont);
    painter.setPen(Qt::white);
    painter.drawText(20, 30, "分数");
    painter.setFont(valueFont);
    painter.setPen(QColor(255, 215, 0)); // 金色
    painter.drawText(20, 80, QString::number(score));

    // 连击显示 - 文字在上，数字在下
    painter.setFont(labelFont);
    painter.setPen(Qt::white);
    painter.drawText(170, 30, "连击");
    painter.setFont(valueFont);

    // 根据连击数改变颜色
    if(combo >= 10) {
        painter.setPen(QColor(255, 50, 50)); // 红色 - 高连击
    } else if(combo >= 5) {
        painter.setPen(QColor(255, 215, 0)); // 金色 - 中等连击
    } else {
        painter.setPen(Qt::yellow); // 黄色 - 低连击
    }
    painter.drawText(170, 80, QString::number(combo));

    // 生命值显示 - 新增
    painter.setFont(labelFont);
    painter.setPen(Qt::white);
    painter.drawText(320, 30, "生命值");
    painter.setFont(valueFont);

    // 根据生命值改变颜色
    if(life > 7) {
        painter.setPen(QColor(0, 255, 0)); // 绿色 - 高生命值
    } else if(life > 3) {
        painter.setPen(QColor(255, 215, 0)); // 黄色 - 中等生命值
    } else {
        painter.setPen(QColor(255, 50, 50)); // 红色 - 低生命值
    }
    painter.drawText(320, 80, QString::number(life));

    // 绘制生命值条 - 新增
    int lifeBarWidth = 200;
    int lifeBarHeight = 20;
    int lifeBarX = 420;
    int lifeBarY = 60;

    // 生命值条背景
    painter.setBrush(QColor(50, 50, 50));
    painter.setPen(Qt::NoPen);
    painter.drawRect(lifeBarX, lifeBarY, lifeBarWidth, lifeBarHeight);

    // 生命值条前景
    int currentLifeWidth = (life * lifeBarWidth) / maxLife;
    QColor lifeColor;
    if(life > 7) lifeColor = QColor(0, 255, 0);      // 绿色
    else if(life > 3) lifeColor = QColor(255, 215, 0); // 黄色
    else lifeColor = QColor(255, 50, 50);            // 红色

    painter.setBrush(lifeColor);
    painter.drawRect(lifeBarX, lifeBarY, currentLifeWidth, lifeBarHeight);

    // 生命值条边框
    painter.setPen(QPen(Qt::white, 2));
    painter.setBrush(Qt::NoBrush);
    painter.drawRect(lifeBarX, lifeBarY, lifeBarWidth, lifeBarHeight);

    // 连击特效显示区域
    int comboEffectX = 650;
    int comboEffectY = 40;

    if(combo > 0) {
        // 绘制连击特效背景
        painter.setBrush(QColor(0, 0, 0, 180)); // 半透明黑色背景
        painter.setPen(QPen(QColor(255, 255, 255, 150), 2));
        painter.drawRoundedRect(comboEffectX, comboEffectY-15, 200, 70,10, 10);

        // 根据连击数显示不同的特效文字
        painter.setFont(QFont("微软雅黑", 16, QFont::Bold));

        if(combo >= 20) {
            painter.setPen(QColor(255, 0, 255)); // 紫色 - 超神
            painter.drawText(comboEffectX + 10, comboEffectY + 15, "🔥 超神连击!");
            painter.setFont(QFont("Arial", 12));
            painter.setPen(Qt::cyan);
            painter.drawText(comboEffectX + 10, comboEffectY + 35, QString("+%1分/击").arg(combo / 5 * 50));
        } else if(combo >= 15) {
            painter.setPen(QColor(255, 50, 50)); // 红色 - 完美
            painter.drawText(comboEffectX + 10, comboEffectY + 15, "⚡ 完美节奏!");
            painter.setFont(QFont("Arial", 12));
            painter.setPen(Qt::yellow);
            painter.drawText(comboEffectX + 10, comboEffectY + 35, QString("+%1分/击").arg(combo / 5 * 50));
        } else if(combo >= 10) {
            painter.setPen(QColor(255, 215, 0)); // 金色 - 火热
            painter.drawText(comboEffectX + 10, comboEffectY + 25, "🌟 火热状态!");
            painter.setFont(QFont("Arial", 12));
            painter.setPen(Qt::green);
            painter.drawText(comboEffectX + 10, comboEffectY + 35, QString("+%1分/击").arg(combo / 5 * 50));
        } else if(combo >= 5) {
            painter.setPen(QColor(0, 255, 255)); // 青色 - 良好
            painter.drawText(comboEffectX + 10, comboEffectY + 15, "🎯 节奏良好!");
            painter.setFont(QFont("Arial", 12));
            painter.setPen(Qt::white);
            painter.drawText(comboEffectX + 10, comboEffectY + 35, QString("+%1分/击").arg(combo / 5 * 50));
        } else {
            painter.setPen(QColor(144, 238, 144)); // 浅绿色 - 开始
            painter.drawText(comboEffectX + 10, comboEffectY + 15, "✨ 连击开始");
            painter.setFont(QFont("Arial", 12));
            painter.setPen(QColor(200, 200, 200));
            painter.drawText(comboEffectX + 10, comboEffectY + 35, "保持节奏获得奖励!");
        }

        // 绘制连击进度条
        int progressWidth = 180;
        int currentProgress = combo % 5; // 0-4
        int progress = (currentProgress * progressWidth) / 5;

        painter.setBrush(QColor(50, 50, 50)); // 背景条
        painter.setPen(Qt::NoPen);
        painter.drawRect(comboEffectX + 10, comboEffectY + 40, progressWidth, 8);

        // 进度条颜色根据连击等级变化
        QColor progressColor;
        if(combo >= 10) progressColor = QColor(255, 50, 50);
        else if(combo >= 5) progressColor = QColor(255, 215, 0);
        else progressColor = QColor(0, 255, 0);

        painter.setBrush(progressColor);
        painter.drawRect(comboEffectX + 10, comboEffectY + 40, progress, 8);
    } else {
        // 没有连击时的显示
        painter.setFont(QFont("微软雅黑", 14));
        painter.setPen(QColor(150, 150, 150));
        painter.drawText(comboEffectX + 10, comboEffectY + 15, "开始击球获得连击!");
    }

    // 操作提示放在右下角
    painter.setFont(QFont("Arial", 12));
    painter.setPen(QColor(255, 215, 0));
    painter.drawText(width() - 150, 30, "操作: D F J K");

    // 重新开始提示
    painter.setPen(QColor(255, 215, 0));
    painter.drawText(width() - 150, 50, "R键重新开始");

    // 绘制判定文字
    drawJudgements(painter);
}

// 绘制判定文字
void MainWindow::drawJudgements(QPainter &painter)
{
    for(const JudgementDisplay &judge : judgementDisplays) {
        // 根据判定等级设置不同的字体样式
        QFont font("微软雅黑", 16, QFont::Bold);

        if(judge.type == HOMERUN) {
            font.setPointSize(20);
            font.setBold(true);
            painter.setPen(QPen(judge.color, 3));
        } else if(judge.type == GOODBALL) {
            font.setPointSize(18);
            font.setBold(true);
            painter.setPen(QPen(judge.color, 2));
        } else if(judge.type == SINGLEHIT) {
            font.setPointSize(16);
            painter.setPen(QPen(judge.color, 2));
        } else {
            font.setPointSize(14);
            painter.setPen(QPen(judge.color, 1));
        }

        painter.setFont(font);

        // 绘制文字背景（可选，让文字更清晰）
        painter.setBrush(QColor(0, 0, 0, 150)); // 半透明黑色背景
        painter.setPen(Qt::NoPen);
        QRect textRect = QFontMetrics(font).boundingRect(judge.text);
        textRect.moveCenter(QPoint(judge.x, judge.y));
        textRect.adjust(-5, -2, 5, 2);
        painter.drawRect(textRect);

        // 绘制判定文字
        painter.setPen(QPen(judge.color, 2));
        painter.drawText(judge.x - textRect.width()/2, judge.y + textRect.height()/4, judge.text);
    }
}
